package com.iam.core.utils;

import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author camel
 */
public class SaTokenUtils implements StpInterface {
    @Autowired
    private SaTokenDao saTokenDao;

    public List<String> getPermissionList(String tokenValue) {
        if (StringUtils.isEmpty(tokenValue)) {
            tokenValue = StpUtil.getTokenValue();
        }
        if (StringUtils.isEmpty(tokenValue)) {
            return new ArrayList<>();
        }
        String permissionStr = saTokenDao.get("x-token:login:permission:" + tokenValue);
        if (StringUtils.isEmpty(permissionStr)) {
            return new ArrayList<>();
        }
        return (List<String>) CollectionUtils.arrayToList(permissionStr.split(","));
    }

    public List<String> getRoleList(String tokenValue) {
        if (StringUtils.isEmpty(tokenValue)) {
            tokenValue = StpUtil.getTokenValue();
        }
        if (StringUtils.isEmpty(tokenValue)) {
            return new ArrayList<>();
        }
        String roleStr = saTokenDao.get("x-token:login:role:" + tokenValue);
        if (StringUtils.isEmpty(roleStr)) {
            return new ArrayList<>();
        }
        return (List<String>) CollectionUtils.arrayToList(roleStr.split(","));
    }

    @Override
    public List<String> getPermissionList(Object o, String s) {
        return getPermissionList(null);
    }

    @Override
    public List<String> getRoleList(Object o, String s) {
        return getRoleList(null);
    }
}
